const Koa = require('koa');
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const cp = require("child_process");
const webpackConfig = require('../lib/webpack.config');
var PassThrough = require('stream').PassThrough;
var Readable = require('stream').Readable;
function RR(){
  Readable.call(this,arguments);
}
RR.prototype = new Readable();
RR.prototype._read = function(data){
}

// const stream = new RR()//PassThrough();
// const sse = (stream,event, data) => {
//   return stream.push(`event:${ event }\ndata: ${ JSON.stringify(data) }\n\n`)
// }


const app = new Koa();
const bodyParser = require('koa-bodyparser');



app.use(bodyParser({
  formLimit: '50mb',
}));

app.use(async (ctx, next) => {

  if(ctx.method === 'GET') {
    await dealGetRequest(ctx); 
  }
  if(ctx.request.method === 'POST' ) {
    await dealPostRequest(ctx)
  } 

  // if(ctx.request.url === '/update') {
  //   ctx.set({
  //       'Content-Type':'text/event-stream',
  //       'Cache-Control':'no-cache',
  //       'Connection': 'keep-alive'
  //   });
  //   ctx.body = stream;
  // }
  await next();
});


/** 处理get请求 */
async function dealGetRequest(ctx) {
  // 入口请求
  if(ctx.request.url === '/' || ctx.request.url === '/index' ) {
    ctx.body = fs.readFileSync(path.join(process.cwd(), 'dist', 'index.html'), {
      encoding: 'utf-8'
    });
    return;
  }
  // 简单处理静态资源
  if(ctx.request.url.indexOf('.') !== -1) {
    ctx.body = fs.readFileSync(path.join(process.cwd(), 'dist', ctx.request.url), {
      encoding: 'utf-8'
    });
    return;
  }
}
/** 处理post请求 */
async function dealPostRequest(ctx) {
  if(ctx.request.url === '/saveCode') {
    const {code, filename} = ctx.request.body;     
    // 重写文件
    fs.writeFileSync(path.join(process.cwd(), 'src', 'preview', filename), code);
    // 运行webpack
    cp.execSync('npm run build', {
      encoding: 'utf-8',
    })
    // sse(stream, 'edit', {code: fs.readFileSync(path.join(process.cwd(), 'src', 'preview', filename), {encoding: 'utf-8'})});
    ctx.body = {
      code: 0,
      data: null,
      msg: '成功'
    }  
  }
}



app.listen(3000);